<template>
  <a-modal class="import-excel" title="导入EXCEL" :width="600" :visible="visible" :confirmLoading="uploading" :maskClosable="false" :closable="false" @cancel="handleClose">
    <div style="margin: 0px 0px 5px 1px" v-if="online">
      <span style="display: inline-block;height: 32px;line-height: 32px;vertical-align: middle;">是否开启校验:</span>
      <span style="display: inline-block;height: 32px;margin-left: 6px">
        <a-switch :checked="validateStatus == 1" @change="handleChangeValidateStatus" checked-children="是" un-checked-children="否" size="small" />
      </span>
    </div>

    <a-upload
      name="file"
      :action="uploadParams.actionUrl"
      :headers="uploadParams.headers"
      :data="formKeyData"
      :multiple="isMultiple"
      accept=".xls,.xlsx"
      :fileList="fileList"
      :remove="handleRemove"
      :beforeUpload="beforeUpload"
      @change="handleChange"
    >
      <a-button>
        <a-icon type="upload" />
        选择导入文件
      </a-button>
    </a-upload>
    <a :href="templateUrl" v-if="templateUrl" class="template"><a-icon type="vertical-align-bottom" />下载模板</a>
    <template slot="footer">
      <a-button @click="handleClose" :disabled="uploading">关闭</a-button>
      <a-button type="primary" @click="handleImport" :disabled="fileList.length === 0" :loading="uploading">
        确定
      </a-button>
    </template>
  </a-modal>
</template>

<script>
import { importFile } from '@/api/marketingCenter/invite.js'
import { uploadToken } from '@/api/api'
export default {
  name: 'JImportModal',
  props: {
    url: {
      type: String,
      default: '',
      required: false
    },
    biz: {
      type: String,
      default: '',
      required: false
    },
    //是否online导入
    online: {
      type: Boolean,
      default: false,
      required: false
    },
    // 导入模板下载
    templateUrl: {
      type: String,
      default: '',
      required: false
    },
    isMultiple: {
      type: Boolean,
      default: false,
      required: false
    },
    // 区分业务
    serviceId: {
      type: Number,
      default: null,
      required: false
    },
    uploadParams: {
      type: Object,
      default: null,
      required: false
    },
    id: {
      default: '',
      required: false
    },
    type: {
      default: '',
      required: false
    },
    fileSize: {
      type: Number,
      required: false,
      default: 1
    }
  },
  data() {
    return {
      visible: false,
      uploading: false,
      fileList: [],
      uploadAction: '',
      validateStatus: 0,
      formKeyData: {
        token: '',
        key: ''
      },
      token: '',
      uploadHost: this.uploadParams.uploadHost
    }
  },
  watch: {
    url(val) {
      if (val) {
        this.uploadAction = window._CONFIG['domianURL'] + val
      }
    }
  },
  created() {
    this.fetchUploadToken()
    this.uploadAction = window._CONFIG['domianURL'] + this.url
  },

  methods: {
    fetchUploadToken() {
      uploadToken().then(res => {
        if (res.code == 0) {
          this.token = res.data
        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    handleClose() {
      this.visible = false
    },
    show(arg) {
      this.fileList = []
      this.uploading = false
      this.visible = true
      this.validateStatus = 0
    },
    handleRemove(file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < this.fileSize
      if (!isLt2M) {
        this.$message.error(`文件请小于${this.fileSize}MB!`)
        return new Promise((resolve, reject) => {
          reject()
        })
      }
      if (this.isMultiple) {
        this.fileList = [...this.fileList, file]
      } else {
        this.fileList = [file]
      }

      const key = new Date().getTime() + '-' + file.name
      this.formKeyData = {
        key: key,
        token: this.token
      }
      return true
    },
    handleChange(info) {
      console.log(info,'info')
      let fileList = []
      if (this.isMultiple) {
        fileList = [...info.fileList]
      } else {
        fileList = info.fileList
      }

      fileList = fileList.map(file => {
        if (file.response) {
          file.url = this.uploadHost + file.response.key
          console.log('上传成功', file.response)
        }
        return file
      })

      this.fileList = fileList
    },
    handleImport() {
      const { fileList } = this
      let file = fileList[0].originFileObj
      let id = this.id
      let type = this.type
      const formData = new FormData()
      formData.append('file', file)
      formData.append('id', id)
      formData.append('type', type)
      this.uploading = true
      console.log(formData);
      importFile(formData).then(res => {
        if (res.code == 200) {
          this.$emit('ok', res.msg)
        }
      })
    },
    // 是否开启校验 开关改变事件
    handleChangeValidateStatus(checked) {
      this.validateStatus = checked == true ? 1 : 0
    },
    // 错误信息提示
    errorTip(tipMessage, fileUrl) {
      const h = this.$createElement
      let href = window._CONFIG['domianURL'] + fileUrl
      this.$warning({
        title: '导入成功,但是有错误数据!',
        content: h('div', {}, [
          h('div', tipMessage),
          h('span', '具体详情请 '),
          h(
            'a',
            {
              attrs: {
                href: href,
                target: '_blank'
              }
            },
            '点击下载'
          )
        ]),
        onOk() {}
      })
    },
    close() {
      this.handleClose()
    }
  }
}
</script>

<style lang="less" scoped>
.import-excel {
  /deep/ .ant-modal-body {
    display: flex !important;
  }
  .template {
    line-height: 32px;
    margin-left: 12px;
  }
}
</style>

